#include "./winstub.h"
#include "utils/strutils.h"

using namespace MiniUI;

namespace
{
    const wchar_t * g_cfileMode[] = {L"rb", L"wb", L"ab", L"rb+", L"wb+", L"ab+", L"rb", L"rb"};
}

WinStub::WinStub(const char* szFileName, uint nflag)
: BaseIOStub(szFileName, nflag)
, m_file(nullptr)
{
    OpenFile(szFileName, nflag);
}

WinStub::~WinStub()
{
    if (m_file)
    {
        fclose(m_file);
    }
}

size_t WinStub::Read(void* buf, size_t size)
{
    return fread(buf, 1, size, m_file);
}

size_t WinStub::Write(const void* buf, size_t size)
{
    return fwrite(buf, 1, size, m_file);
}

uint WinStub::Tell()
{
    return ftell(m_file);
}

int WinStub::Seek(int offset, int origin)
{
    return fseek(m_file, offset, origin);
}

#pragma warning(disable:4748)  
bool WinStub::OpenFile(const char* szFileName, uint uflag)
{
    uint uflagraw = uflag & 0x7;

    std::wstring wstr;
    Unicode::UTF8Decode(szFileName, wstr);

    m_file = _wfopen(wstr.c_str(), g_cfileMode[uflagraw]);
    return m_file ? true : false;
}
#pragma warning(default:4748)